import React from "react";
import {
  Form,
  Input,
  Button,
  Modal,
  DatePicker,
  Transfer,
  message,
  Tag,
  Select,
  Radio,
} from "antd";
import moment from "moment";
import axios from "axios";
import qs from "qs";
import "../mock/meetingdata";
import "antd/dist/antd.css";
import OrgTree from "./OrgTree";
const { Option } = Select;

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S+": this.getMilliseconds(), //毫毛
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default class AddMeeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      // mockData: ['李亮','张明','李飞','王培'],//职工列表
      hostMockData: [], //职工列表
      joinMockData: [], //职工列表
      hostTargetKeys: [],
      joinTargetKeys: [],
      rules: [
        {
          required: true,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      changeDataSource: props.changeDataSource,
    };
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  formRef = React.createRef();
  /**弹出对话框 */
  showAddModal = () => {
    this.setState({
      addVisible: true,
    });
  };
  /**添加主持人 */
  handleHostChange = (hostTargetKeys) => {
    this.setState({ hostTargetKeys });
  };
  /**添加参会人 */
  handleJoinChange = (joinTargetKeys) => {
    this.setState({ joinTargetKeys });
  };

  // 获取职工树
  getTreedata = () => {
    const treeData = this.getTree(this.props.staffList);
    this.setState({ treeData });
  };
  getTree = (value) => {
    if (value.length) {
      return value.map((item, i) => {
        return {
          key: item.depId,
          title: item.depName,
          value: item.data,
          children: this.getTree(item.children),
        };
      });
    }
  };

  componentDidMount() {}

  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };
  /*点击部门列表,展示部门人员 */
  treeOnSelect = (isHost, value) => {
    console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          if (isHost) {
            this.setState({
              hostMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          } else {
            this.setState({
              joinMockData: res.map((person) => {
                return {
                  key: person.EMPID + "_" + person.EMPNAME,
                  title: person.EMPID + "_" + person.EMPNAME,
                };
              }),
            });
          }
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };
  /**关闭Tag */
  handleHostTagClose = (removedTag) => {
    const hostTargetKeys = this.state.hostTargetKeys.filter(
      (hostTargetKeys) => hostTargetKeys !== removedTag
    );
    console.log(hostTargetKeys);
    this.setState({ hostTargetKeys });
  };
  handleJoinTagClose = (removedTag) => {
    const joinTargetKeys = this.state.joinTargetKeys.filter(
      (joinTargetKeys) => joinTargetKeys !== removedTag
    );
    console.log(joinTargetKeys);
    this.setState({ joinTargetKeys });
  };
  /*遍历插入Tag */
  hostForMap = (tag) => {
    console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="geekblue"
          onClose={(e) => {
            e.preventDefault();
            this.handleHostTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };
  joinForMap = (tag) => {
    console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleJoinTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  onFinish = (values) => {
    // 进入提交
    this.setState({ loading: true });
    /**提醒时间 */
    let meetingDate = values.date._d.getTime();
    let remindTime = new Date(
      meetingDate - values.remindTime * 60 * 1000
    ).Format("yyyy-MM-dd HH:mm:ss");
    let enable = 0;
    if (values.enable) {
      enable = values.enable;
    }
    /**添加会议数据 */

    axios
      .post(
        "addMeetingSchoool.rst ",
        qs.stringify({
          meetingDate: values.date.format("YYYY-MM-DD"),
          meetingTime: values.date.format("HH:mm"),
          host: this.state.hostTargetKeys.join(),
          participator: this.state.joinTargetKeys.join(),
          locale: values.address,
          theme: values.content,
          meetingRoom: values.meetingRoom,
          remindTime: remindTime,
          enable: enable,
        })
      )
      .then((res) => {
        let response = res.data;
        if (response.resultCode === 0) {
          /**清空并关闭添加表单 */
          this.formRef.current.resetFields();
          this.setState({
            hostTargetKeys: [],
            joinTargetKeys: [],
            loading: false,
            addVisible: false,
          });
          /**重新渲染会议列表 */
          this.props.getDataSource();
          message.success("提交成功");
        } else {
          this.setState({ loading: false, addVisible: false });
          message.error("提交失败");
        }
      })
      .catch((error) => {
        this.setState({ loading: false, addVisible: false });
        message.error("提交失败");
      });
  };
  render() {
    const { addVisible, loading } = this.state;
    /**添加会议数据 */

    const handleCancel = () => {
      /**清空修改表单状态 */
      this.formRef.current.resetFields();
      this.setState({
        hostTargetKeys: [],
        joinTargetKeys: [],
        loading: false,
        addVisible: false,
      });
    };
    const {
      rules,
      hostTargetKeys,
      joinTargetKeys,
      treeData,
      hostMockData,
      joinMockData,
    } = this.state;
    const hostTag = hostTargetKeys.map(this.hostForMap);
    const joinTag = joinTargetKeys.map(this.joinForMap);
    return (
      <>
        <Button type="primary" onClick={this.showAddModal}>
          增加
        </Button>
        <Modal
          /**对话框属性 */
          visible={addVisible}
          title="添加会议"
          centered
          onCancel={handleCancel}
          width={1000}
          footer={null}
          className="edit-modal"
          destroyOnClose={true}
        >
          <Form
            name="add-meeting"
            onFinish={this.onFinish} /**表单提交事件 */
            class="search-meet"
            ref={this.formRef}
          >
            <Form.Item name="date" label="会议时间" rules={rules}>
              <DatePicker
                format="YYYY-MM-DD HH:mm"
                showTime={{ defaultValue: moment("12:00:00", "HH:mm") }}
              />
            </Form.Item>
            <Form.Item name="remindTime" label="提醒时间">
              <Select
                style={{ width: 180 }}
                allowClear
                // dropdownRender={(menu) => (
                //   <div>
                //     {menu}
                //     <Divider style={{ margin: "4px 0" }} />
                //     <div
                //       style={{
                //         display: "flex",
                //         flexWrap: "nowrap",
                //         padding: 8,
                //       }}
                //     >
                //       <DatePicker
                //         format="YYYY-MM-DD HH:mm"
                //         showTime={{ defaultValue: moment("12:00:00", "HH:mm") }}
                //       />
                //     </div>
                //   </div>
                // )}
              >
                <Option value="10">提前10分钟</Option>
                <Option value="15">提前15分钟</Option>
                <Option value="30">提前30分钟</Option>
                <Option value="60">提前60分钟</Option>
              </Select>
            </Form.Item>
            <Form.Item name="address" label="地点" rules={rules}>
              <Input />
            </Form.Item>
            <Form.Item name="meetingRoom" label="会议室">
              <Input />
            </Form.Item>
            <Form.Item name="content" label="内容" rules={rules}>
              <Input />
            </Form.Item>
            <Form.Item name="host" label="主持人">
              {hostTag}
              <OrgTree
                treeData={treeData}
                setTreeData={this.setTreeData}
                treeOnSelect={this.treeOnSelect}
                isHost={true}
              />
              <Transfer
                /**穿梭框属性，数据源为职工列表 */
                dataSource={hostMockData}
                targetKeys={hostTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleHostChange}
                render={(item) => `${item.title}`}
                disabled={hostTargetKeys.length}
              />
            </Form.Item>
            <Form.Item name="join" label="参加人">
              {joinTag}
              <OrgTree
                treeData={treeData}
                setTreeData={this.setTreeData}
                treeOnSelect={this.treeOnSelect}
                isHost={false}
              />
              <Transfer
                dataSource={joinMockData}
                targetKeys={joinTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleJoinChange}
                render={(item) => `${item.title}`}
              />
            </Form.Item>
            <Form.Item name="enable" label="是否启用">
              <Radio.Group name="enable" defaultValue={0}>
                <Radio value={1}>启用</Radio>
                <Radio value={0}>不启用</Radio>
              </Radio.Group>
            </Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
          </Form>
        </Modal>
      </>
    );
  }
}
